//
//  ApplyViewController.m
//  ZiJinLian
//
//  Created by 🐛 on 2017/4/13.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "ApplyViewController.h"
#import "InformationTableViewCell.h"
#import "PictureTableViewCell.h"
#import "CardTableViewCell.h"
#import "AddressPickerView.h"


@interface ApplyViewController ()<UITableViewDelegate,UITableViewDataSource,AddressPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>

@property (nonatomic ,strong) AddressPickerView * pickerView;
@property (nonatomic ,strong) UITableView * tableView;
@property (nonatomic ,strong) NSArray     * name;
@property (nonatomic ,strong) NSArray     * array;
@property (nonatomic ,strong) UIButton    * addressBtn;
@property (nonatomic ,strong) UITextField * textField;
@property (nonatomic ,strong) UIButton    * picBtn;
@property (nonatomic ,strong) UITextField * userField;
@property (nonatomic ,strong) UITextField * numField;
@property (nonatomic ,strong) UITextField * cardField;
@property (nonatomic ,strong) UITextField * regionField;
@property (nonatomic ,strong) UITextField * nameField;
@property (nonatomic ,strong) UITextField * legaField;
@property (nonatomic ,strong) NSMutableArray *imagArry;
@property (nonatomic ,strong) NSMutableArray *imagArray;
@property (nonatomic ,strong) UIImage *cardImage;
@property (nonatomic ,strong) UIImage *frontImage;
@property (nonatomic ,strong) UIImage *backImage;
@property (nonatomic ,strong) NSString *province;
@property (nonatomic ,strong) NSString *city;
@property (nonatomic ,strong) NSString *district;


@end

@implementation ApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imagArry=[NSMutableArray array];//身份证
    self.imagArray=[NSMutableArray array];//营业执照
    self.name=[NSArray arrayWithObjects:MyString(@"姓名"),MyString(@"联系电话"),MyString(@"身份证号"),MyString(@"申请地区"), nil];
    self.array=[NSArray arrayWithObjects:MyString(@"名称"),MyString(@"法人代表"), nil];
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MainW, MainH-64) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.backgroundColor=Gray_Color;
    tableView.dataSource = self;
    tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    tableView.separatorColor=SeparatorColor;
    tableView.separatorInset=UIEdgeInsetsZero;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [self.view addSubview:self.pickerView];
    [tableView registerNib:[UINib nibWithNibName:@"InformationTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"InformationTableViewCell"];
    [tableView registerNib:[UINib nibWithNibName:@"PictureTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"PictureTableViewCell"];
    [tableView registerNib:[UINib nibWithNibName:@"CardTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"CardTableViewCell"];
}
- (AddressPickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[AddressPickerView alloc]initWithFrame:CGRectMake(0, MainH-64  , MainW, 215)];
        _pickerView.delegate = self;
    }
    return _pickerView;
}
#pragma mark -------- tableviewdelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return self.name.count;
    }else if (section==1){
        return self.array.count;
    }else{
        return 1;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0||indexPath.section==1) {
        return 50;
    }else if (indexPath.section==2){
        return 100;
    }else{
        return 200;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0||section==1) {
        return 40;
    }else{
        return 46;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        InformationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"InformationTableViewCell"];
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"InformationTableViewCell"];
        }
        cell.titleName.text=self.name[indexPath.row];
        cell.textField.delegate=self;
        switch (indexPath.row) {
            case 0:
            {
                self.userField=cell.textField;
            }
                break;
            case 1:
            {
                 self.numField=cell.textField;
            }
                break;
            case 2:
            {
                 self.cardField=cell.textField;
            }
                break;
            case 3:
            {
                cell.textField.enabled=NO;
                cell.arrow.hidden=NO;
                cell.Clickbtn.hidden=NO;
                self.addressBtn=cell.Clickbtn;
                self.textField=cell.textField;
                [cell.Clickbtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            }
                break;
                
            default:
                break;
        }
        return cell;
    }else if (indexPath.section==1) {
        InformationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"InformationTableViewCell"];
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"InformationTableViewCell"];
        }
        cell.textField.delegate=self;
        switch (indexPath.row) {
            case 0:
            {
                 self.nameField=cell.textField;
            }
            case 1:
            {
                self.legaField=cell.textField;
            }

                break;
                
            default:
                break;
        }
        cell.titleName.text=self.array[indexPath.row];
        return cell;
    }else if(indexPath.section==2){
        PictureTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"PictureTableViewCell"];
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"PictureTableViewCell"];
        }
        [cell.uploadPic addTarget:self action:@selector(changeIconImg:) forControlEvents:UIControlEventTouchUpInside];
        cell.uploadPic.tag=1;
        return cell;
    }else{
        CardTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CardTableViewCell"];
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"CardTableViewCell"];
        }
        [cell.frontBtn addTarget:self action:@selector(changeIconImg:) forControlEvents:UIControlEventTouchUpInside];
        cell.frontBtn.tag=2;
        cell.versoBtn.tag=3;
        [cell.versoBtn addTarget:self action:@selector(changeIconImg:) forControlEvents:UIControlEventTouchUpInside];
        [cell.SureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }

    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0||section==1) {
        UIView *view=[[UIView alloc]init];
        view.backgroundColor=Gray_Color;
        MYLabel*label=[[MYLabel alloc]initWithFrame:CGRectMake(10, 15, MainW-10, 20)];
        if (section==0) {
            label.text=MyString(@"个人信息");
        }else{
            label.text=MyString(@"营业执照");
        }
        label.backgroundColor=[UIColor clearColor];
        label.textColor=TextColor3;
        [view addSubview:label];
        return view;
    }else{
        UIView *view=[[UIView alloc]init];
        view.backgroundColor=Gray_Color;
        MYLabel*label=[[MYLabel alloc]initWithFrame:CGRectMake(0, 13, MainW, 33)];
        if (section==2) {
            label.text=MyString(@"营业执照照片");
        }else{
            label.text=MyString(@"身份证照片");
        }
        label.backgroundColor=[UIColor whiteColor];
        label.textColor=TextColor3;
        UIView*line=[[UIView alloc]init];
        line.backgroundColor=Gray_Color;
        line.frame=CGRectMake(0, 46, MainW, 1);
        [view addSubview:line];
        [view addSubview:label];

        return view;
    }
}
-(NSArray *)arrayWithMemberIsOnly:(NSArray *)array
{
    NSMutableArray *categoryArray = [[NSMutableArray alloc] init];
    for (unsigned i = 0; i < [array count]; i++) {
        @autoreleasepool {
            if ([categoryArray containsObject:[array objectAtIndex:i]] == NO) {
                [categoryArray addObject:[array objectAtIndex:i]];
            }
        }
    }
    return categoryArray;
}
#pragma mark ---------- 确定按钮
- (void)sureBtnClick{
	BOOL isLogin=[ZJUserDefaultsTools isLogin];

	if (!isLogin){
		ZJLoginViewController *controller = [[ZJLoginViewController alloc] init];
		ZJBaseNavControllerViewController* nav=[[ZJBaseNavControllerViewController alloc]initWithRootViewController:controller];
		controller.modality=NO;
		[self presentViewController:nav animated:YES completion:nil];
		return;
	}
	
	
	
    //NSLog(@"名字:%@,电话:%@,身份证:%@,地区:%@,名称:%@,法人代表:%@,",self.userField.text,self.numField.text,self.cardField.text,self.textField.text,self.nameField.text,self.legaField.text);
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"name"]=self.userField.text;
    dic[@"phone"]=self.numField.text;
    dic[@"id"]=self.cardField.text;
    dic[@"province"]=self.province;
    dic[@"city"]=self.city;
    dic[@"district"]=self.district;
    NSString*userInfo=[self convertToJsonData:dic];
    NSMutableDictionary*dictionary=[NSMutableDictionary dictionary];
    dictionary[@"name"]=self.nameField.text;
    dictionary[@"corporation"]=self.legaField.text;
    NSString*businessLicence=[self convertToJsonData:dictionary];
    if (self.cardImage==nil||self.backImage==nil||self.frontImage==nil||self.userField.text.length==0||self.numField.text.length==0||self.cardField.text.length==0||self.nameField.text.length==0||self.legaField.text.length==0) {
        [self showToast:MyString(@"申请资料")];
        return;
    }
    [self showDialog];
    NSString*urlString=[NSString stringWithFormat:@"%@%@",baseURL,@"/api/member/agent/apply"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         
                                                         @"text/html",
                                                         
                                                         @"image/jpeg",
                                                         
                                                         @"image/png",
                                                         
                                                         @"application/octet-stream",
                                                         
                                                         @"text/json",
                                                         
                                                         nil];
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 上传的参数名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
       
                NSData * imageData = UIImageJPEGRepresentation(self.cardImage, 0.5);
                [formData appendPartWithFileData:imageData name:@"licenceImage" fileName:fileName mimeType:@"image/jpeg"];
                NSData * imageData1 = UIImageJPEGRepresentation(self.frontImage, 0.5);
                [formData appendPartWithFileData:imageData1 name:@"cardFront" fileName:fileName mimeType:@"image/jpeg"];
                NSData * imageData2 = UIImageJPEGRepresentation(self.backImage, 0.5);
                [formData appendPartWithFileData:imageData2 name:@"cardBack" fileName:fileName mimeType:@"image/jpeg"];

        // 上传 多张图片
        
            [formData appendPartWithFormData:[[NSString stringWithFormat:@"%@",userInfo] dataUsingEncoding:NSUTF8StringEncoding] name:@"userInfo"];
            [formData appendPartWithFormData:[@"zhcn" dataUsingEncoding:NSUTF8StringEncoding] name:@"lang"];
            [formData appendPartWithFormData:[[NSString stringWithFormat:@"%@",businessLicence] dataUsingEncoding:NSUTF8StringEncoding] name:@"businessLicence"];
            [formData appendPartWithFormData:[[NSString stringWithFormat:@"%@",[ZJUserDefaultsTools getCurrentUserID]] dataUsingEncoding:NSUTF8StringEncoding] name:@"userId"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self dismissDialog];
        [MBProgressHUD showSuccess:MyString(@"提交成功!")];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self dismissDialog];
        [MBProgressHUD showError:MyString(@"提交失败!")];
    }];

}
-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
       // NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}
- (void)btnClick:(UIButton *)btn{
    [self.view endEditing:YES];
    btn.selected = !btn.selected;
    if (btn.selected) {
        [self.pickerView show];
    }else{
        [self.pickerView hide];
    }
}
#pragma mark - AddressPickerViewDelegate
- (void)cancelBtnClick{
    [self btnClick:_addressBtn];
}
- (void)sureBtnClickReturnProvince:(NSString *)province City:(NSString *)city Area:(NSString *)area{
    self.textField.text=[NSString stringWithFormat:@"%@%@%@",province,city,area];
    self.province=province;
    self.city=city;
    self.district=area;
    [self btnClick:_addressBtn];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [self.pickerView hide];
    self.addressBtn.selected=NO;
}
- (void)changeIconImg:(UIButton *)sender
{
    [self.pickerView hide];
    self.addressBtn.selected=NO;
    self.picBtn=sender;
    UIAlertController* alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    /*UIAlertControllerStyleActionSheet  警告框的样式:底部*/
    [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto]; /*拍照*/
    }]];
    [alertC addAction:[UIAlertAction actionWithTitle:@"我的相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self LocalPhoto]; /*从相册*/
    }]];
    
    [self presentViewController:alertC animated:YES completion:nil];
}
/**
 * 从相册选择
 */
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

/**
 * 拍照
 */
-(void)takePhoto
{
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        [self showToast:@"该设备无摄像头"]; //跳出提示
    }
}
/**
 * 图像选取器的委托方法，选完图片后回调该方法
 */
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    //当图片不为空时显示图片并保存图片
    if (image!= nil)
    {
        if (self.picBtn.tag==1) {
            self.cardImage=image;
            
        }else if(self.picBtn.tag==2){
            self.frontImage=image;
            
        }else{
            self.backImage=image;
        }
        //[self.imagArry insertObject:image atIndex:self.picBtn.tag];
        
        [self.picBtn setBackgroundImage:image forState:UIControlStateNormal];
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
}
// 相机选择取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)changeFaceImg:(NSString *)userimg small:(NSString *)userlittleimg userid:(NSString *)userid
{
    
    
}

@end
